package com.demo.rabbitmq.demo01;

import com.demo.rabbitmq.contanst.Constant;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 接收者
 * @author liangliang
 */
public class Receive {

    public static void execute(String host, String username, String password) {

        // 配置连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(host);
        // 需要在管理后台增加hry账号
        factory.setUsername(username);
        factory.setPassword(password);

        Connection connection = null;
        Channel channel = null;

        try {
            // 建立TCP连接
            connection = factory.newConnection();
            // 在TCP基础上创建信道
            channel = connection.createChannel();
            // 声明一个队列
            channel.queueDeclare(Constant.QUEUE_NAME, false, false, false, null);
            System.out.println("[Receiving Message]...");
            channel.basicQos(1);

            // 默认消费实现
            Consumer consumer = new DefaultConsumer(channel) {
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                                           byte[] body) throws IOException {
                    String message = new String(body, "UTF-8");
                    System.out.println("[Received] : " + message);
                }
            };
            // 接收消息
            channel.basicConsume(Constant.QUEUE_NAME,true, consumer);

        } catch (IOException | TimeoutException e) {
            // 不能关闭连接，关闭后不能接收到后续来的消息
            e.printStackTrace();
        }

    }
}
